//
//  PopoverPresentationManager.swift
//  WBDemo
//
//  Created by Meng on 17/1/21.
//  Copyright © 2017年 demo. All rights reserved.
//

import UIKit



class PopoverPresentationManager: NSObject, UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    
    var isPresent = false // 是否展现
    // MARK: - UIViewControllerTransitioningDelegate
    // 该方法返回一个负责转场动画的对象
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return PopoverPresentationController(presentedViewController: presented, presenting: presenting)
    }
    
    // 该方法返回一个负责转场如何出现的对象
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = true
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: PopoverPresentationManagerDidPresented), object: nil)
        return self
    }
    
    // 该方法返回一个负责转场如何消失的对象
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresent = false
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: PopoverPresentationManagerDidDismissed), object: nil)
        return self
    }
    // MARK: - UIViewControllerAnimatedTransitioning
    // 告诉系统展现和消失的动画时长
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5
    }
    
    // 用于管理modal如何展现和消失
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        
        if isPresent { // 展现
            guard let toView = transitionContext.view(forKey: .to) else {
                return
            }
            transitionContext.containerView.addSubview(toView)
            // 设置锚点
            toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0.0)
            toView.transform = CGAffineTransform.init(scaleX: 1.0, y: 0.0)
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                toView.transform = CGAffineTransform.identity
            }) { (_) in
                // 告诉系统动画执行完毕了
                transitionContext.completeTransition(true)
            }
        } else { // 消失
            guard let fromView = transitionContext.view(forKey: .from) else {
                return
            }
            UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: {
                fromView.transform = CGAffineTransform.init(scaleX: 1.0, y: 0.00001)
            }, completion: { (_) in
                transitionContext.completeTransition(true)
            })
        }
        
        
    }
    
}
